package com.template.mongo.utils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;

public class EncodingPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessAfterInitialization(Object bean, String name)
			throws BeansException {
		if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                	List<MediaType> mediaTypes = new ArrayList<MediaType>();
                	
                	mediaTypes.add(new MediaType("text", 
                			"plain", 
                            Charset.forName("UTF-8")));
                	
                	mediaTypes.add(new MediaType("application", 
                			"json", 
                            Charset.forName("UTF-8")));
                	
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(mediaTypes);
                }
            }
        }
        return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(Object arg0, String arg1)
			throws BeansException {
		// TODO Auto-generated method stub
		return arg0;
	}
}
